package com.learner.filesystem.controller.api;

import com.learner.common.exception.ExceptionUtil;
import com.learner.common.exception.RestException;
import com.learner.filesystem.service.FileService;
import com.learner.pojo.filesystem.FileSystem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: 文件上传
 * @Author: ice2020x
 * @Date: 2021/10/5
 */
@RequestMapping("/api/oss/file")
@RestController
@Slf4j
public class FileController {
    @Autowired
    private FileService fileService;


    @PostMapping("/upload")
    public FileSystem upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "model") String model) {
        if (file.isEmpty()) {
            throw ExceptionUtil.createException(RestException.class, 4100001);
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw ExceptionUtil.createException(RestException.class, 4100002);
        }

        String originalFilename = file.getOriginalFilename();
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileSize(file.getSize());
        fileSystem.setFileName(file.getOriginalFilename());
        return fileService.upload(inputStream, model, originalFilename, fileSystem);
    }


    @DeleteMapping("/remove")
    public void removeFile(@RequestBody String url) {
        log.info("删除文件,url:{}", url);
        fileService.removeFile(url);
        fileService.removeFileSystem(url);
    }

}
